<template>
  <div v-if="visible">
    <el-dialog :visible.sync="visible"
               :title="hasID == false ? $t('add') + '物联设备' : $t('update') + '物联设备'"
               :modal="false"
               class="user-dialog add-or-updata"
               width="70%"
               :before-close="closeDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form :model="dataForm"
               v-loading="dataListLoading"
               :element-loading-text="$t('loading')"
               ref="dataForm"
               :rules="rules"
               label-position="left"
               @keyup.enter.native="dataFormSubmitHandle()"
               label-width="120px">
        <!-- <div> -->
        <div class="content">
          <div class="title">重要信息</div>
          <div class="line"></div>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="deviceId"
                          label="设备ID">
              <el-input v-model.trim="dataForm.deviceId"
                        :disabled='hasID === true'
                        maxlength="20"
                        show-word-limit
                        placeholder="填写或者系统自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="name"
                          label="设备名称">
              <el-input v-model.trim="dataForm.name"
                        maxlength="20"
                        show-word-limit
                        placeholder="请输入设备名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="subsystem1"
                          label="所属子系统">
              <el-select v-model="dataForm.subsystem1"
                         @change="changes"
                         clearable
                         multiple
                         style="width:100%"
                         placeholder="请选择所属子系统">
                <el-option v-for="item in currentAppMenu"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="deviceType"
                          label="设备类型">
              <el-select v-model="dataForm.deviceType"
                         clearable
                         :disabled='hasID === true'
                         style="width:100%"
                         placeholder="请选择设备类型">
                <el-option v-for="item in $store.state.EquTypeList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="energy"
                          label-width="160px"
                          :rules="required()"
                          label="是否纳入能耗管理">
              <el-radio-group v-model="dataForm.energy">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="false"
                  :span="12">
            <el-form-item prop="status"
                          label="启用/禁用">
              <el-radio-group v-model="dataForm.status">
                <el-radio :label="0">启用</el-radio>
                <el-radio :label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="dockingMethod"
                          label="对接方式"
                          :rules="required()">
              <el-radio-group v-model="dataForm.dockingMethod">
                <el-radio :label="0"
                          v-if="dataForm.deviceType === 8 || dataForm.deviceType === 10 || dataForm.deviceType === 4 || dataForm.deviceType === 6 || dataForm.deviceType === 7">无</el-radio>
                <el-radio :label="1"
                          v-if="dataForm.deviceType === 5 || dataForm.deviceType === 8 || dataForm.deviceType === 9"
                          id="platformBtn">第三方<slot>
                    <el-select v-model="dataForm.platform"
                               clearable
                               @change="onselect"
                               style="margin-bottom: 10px;"
                               placeholder="请选择">
                      <el-option v-for="item in platformList"
                                 :key="item.id"
                                 :label="item.platformName + '-' + getmanufacturersToString(item.manufacturers)"
                                 :value="item.id">
                      </el-option>
                    </el-select>
                  </slot>
                </el-radio>
                <el-radio :label="2"
                          v-if="dataForm.deviceType === 1 || dataForm.deviceType === 2 || dataForm.deviceType === 3">网关透传</el-radio>
                <el-radio :label="3"
                          disabled>网关主动轮询</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="marks"
                          label="设备描述">
              <el-input type="textarea"
                        maxlength="200"
                        show-word-limit
                        :autosize="{ minRows: 3, maxRows: 4 }"
                        placeholder="请输入内容"
                        v-model="dataForm.marks">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备照片"
                          prop="url">
              <file-upload reg=".(png|jpeg|jpg)$"
                           ref="fileUpload"
                           accept=".jpeg,.jpg,.png"
                           title="上传图片"
                           :limit="3"
                           v-model="dataForm.url"
                           :paramData="{ bucketName: 'EquAccount/images' }"
                           action="/springbootApi/system/oss/upload"
                           uploadType="picture-card"
                           @success="successImgLoad"
                           @remove="handleImgRemove" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12"
                  v-if="dataForm.dockingMethod === 1">
            <el-form-item prop="logicId"
                          label="逻辑ID"
                          :rules="required()">
              <el-autocomplete v-model.trim="dataForm.logicId"
                               :fetch-suggestions="querySearchAsync"
                               :hide-loading="false"
                               style="width: 100%"
                               :debounce="0"
                               :maxlength="100"
                               show-word-limit
                               value-key="cameraName"
                               @select="handleSelect"
                               placeholder="请输入逻辑ID"></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12"
                  v-if="dataForm.deviceType === 5 || dataForm.deviceType === 7">
            <el-form-item prop="unifiedAuthorization"
                          :rules="required()"
                          label-width="180px"
                          label="是否门禁管理统一授权">
              <el-radio-group v-model="dataForm.unifiedAuthorization"
                              :disabled="dataForm.subsystem1.length > 1">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-form-item v-if="dataForm.deviceType === 4 || dataForm.deviceType === 5 || dataForm.deviceType === 7"
                        label="支持授权的方式"
                        prop="authorizationMode1"
                        :rules="required()">
            <el-checkbox-group v-model="dataForm.authorizationMode1">
              <el-checkbox :label="1">人脸</el-checkbox>
              <el-checkbox :label="2">指纹</el-checkbox>
              <el-checkbox :label="3">密码</el-checkbox>
              <el-checkbox :label="4">门卡</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-row>
        <div class="content">
          <div class="title">基础信息</div>
          <div class="line"></div>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="type"
                          label="产品类型">
              <el-select v-model="dataForm.type"
                         clearable
                         style="width:100%"
                         placeholder="请选择产品类型">
                <el-option v-for="item in productTypeList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="model"
                          label="设备型号">
              <el-input v-model.trim="dataForm.model"
                        maxlength="20"
                        show-word-limit
                        placeholder="请输入设备型号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="brandId"
                          :rules="required()"
                          label="品牌">
              <el-select v-model="dataForm.brandId"
                         clearable
                         style="width:100%"
                         placeholder="请选择设备品牌">
                <el-option v-for="item in brandList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="aid"
                          label="所在位置">
              <el-select v-model="dataForm.aid"
                         clearable
                         filterable
                         style="width:100%"
                         placeholder="请选择所在位置">
                <el-option v-for="item in locationList"
                           :key="item.id"
                           :label="item.allName"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="content">
          <div class="title">供应商信息</div>
          <div class="line"></div>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="supplier"
                          label="供应商名称">
              <el-input v-model.trim="dataForm.supplier"
                        maxlength="20"
                        show-word-limit
                        placeholder="设备供应商"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="linkMan"
                          label="联系人">
              <el-input v-model.trim="dataForm.linkMan"
                        maxlength="10"
                        show-word-limit
                        placeholder="设备厂商联系人姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="link"
                          label="联系电话"
                          :rules="phoneAndMobileRuleCanNull()">
              <el-input v-model.trim="dataForm.link"
                        maxlength="11"
                        show-word-limit
                        placeholder="设备厂商联系人电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- </div> -->
      </el-form>
      <template slot="footer">
        <el-button @click="closeDialog()">{{ $t("cancel") }}</el-button>
        <el-button type="primary"
                   :loading="dataListLoading"
                   @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import minFormValidate from '@/mixins/form-validate'
import debounce from 'lodash/debounce'
import fileUpload from '@/components/file-upload/file-upload'
export default {
  mixins: [mixinViewModule, minFormValidate],
  data () {
    return {
      mixinViewModuleOptions: {
        deleteImgURL: '/system/oss/delete',
        getDataListURL: '', // 数据列表接口，API地址
        getDataListIsPage: true, // 数据列表接口，是否需要分页？
        addURL: 'tb/device/insertDevice', // 添加或修改接口，API地址
        updateURL: 'tb/device/updateDevice', // 添加或修改接口，API地址
        getDataInfoURL: 'tb/device/getDevice?id=', // 数据详情，API地址
        deleteURL: '', // 删除接口，API地址
        deleteIsBatch: true, // 删除接口，是否需要批量？
        exportURL: '' // 导出接口，API地址
      },
      tempDeleteFileList: [], // 临时删除的文件
      newEditFileList: [], // 保存在编辑时新增的文件路径
      newThumbnailList: [], // 保存在编辑时新增的thumbnail图路径
      tempThumbnailList: [], // 临时删除的thumbnail图的图片
      visible: false,
      dataForm: {
        name: '', // 设备名称
        subsystem1: [], // 所属子系统
        subsystem: '',
        template: '', // 设备模板的id
        type: '', // 产品类型
        // status: 0, // 0启用，1禁用
        marks: '', // 描述
        url: [], // 图片
        model: '', // 设备型号
        brandId: '', // 品牌
        aid: '', // 所在区域的id
        supplier: '', // 供应商
        linkMan: '', // 联系人
        link: '', // 联系方式
        deviceType: '',
        deviceId: '',
        platform: '',
        energy: 1,
        logicId: '', // 逻辑ID
        logicName: '',
        dockingMethod: 0,
        authorizationMode1: [],
        authorizationMode: '',
        unifiedAuthorization: 1
      },
      currentAppMenu: [
        { id: 4, name: '会务管理系统' },
        { id: 1, name: '宿舍管理系统' },
        { id: 7, name: '访客管理系统' },
        { id: 2, name: '智慧路灯系统' },
        { id: 3, name: '多媒体管理系统' },
        { id: 5, name: '餐饮管理系统' },
        { id: 6, name: '能耗管理系统' },
        { id: 0, name: '集成管理系统' },
        { id: 8, name: '视频监控系统' },
        { id: 9, name: '健身房管理系统' },
        { id: 10, name: '门禁管理系统' }],
      productTypeList: [{ // 产品类型
        id: 1,
        name: '网关设备'
      }, {
        id: 2,
        name: '网关子设备'
      }, {
        id: 3,
        name: '直连设备'
      }],
      EquTempList: [],
      onlineList: [{ // 联网方式
        id: 'Wi-Fi',
        name: 'Wi-Fi'
      }, {
        id: '2G/4G/5G',
        name: '2G/4G/5G'
      }, {
        id: '以太网（有线）',
        name: '以太网（有线）'
      }, {
        id: '其他',
        name: '其他'
      }],
      brandList: [],
      locationList: [], // 所在位置
      rules: {
        name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        subsystem1: [{ required: true, message: '请选择所属子系统', trigger: 'change' }],
        deviceType: [{ required: true, message: '请选择设备类型', trigger: 'blur' }]
        // status: [{ required: true, message: '请选择运行状态', trigger: 'change' }],
      },
      hasID: false,
      manufacturersList: [
        { id: 0, name: '北森' }, // 第三方平台列表
        { id: 1, name: '泛微' },
        { id: 2, name: '企业微信' },
        { id: 3, name: '大华' },
        { id: 4, name: '海康' },
        { id: 5, name: '阿里云' },
        { id: 6, name: 'IPC广播网络平台' }],
      timeout: null,
      logicList: [],
      platformList: [] // 平台
    }
  },
  components: {
    fileUpload
  },
  // watch: {
  //   'dataForm.subsystem1' (newval, oldval) {
  //     if (newval) {
  //       if (newval.length > 1) {
  //         this.dataForm.unifiedAuthorization = 1
  //       }
  //     }
  //   },
  //   'dataForm.platform' (newval, oldval) {
  //     if (newval) {
  //       if (newval.length > 1) {
  //         this.dataForm.type1 = 1
  //       }
  //     }
  //   }
  // },
  mounted () {
  },
  methods: {
    init (data) {
      if (data) {
        this.hasID = true
        this.dataForm = data
        this.dataForm.subsystem1 = data.subsystem.split(',').map(Number) // 回显所属子系统
        // this.dataForm.pFlatform ? this.dataForm.type1 = 1 : this.dataForm.type1 = 0 // 回显对接平台
        if (this.dataForm.logicId) { // 回显逻辑ID
          if (this.dataForm.platform) {
            this.getlogicList()
            setTimeout(() => {
              let obj = this.logicList.find(item => item.cameraIndexCode === this.dataForm.logicId)
              if (obj) {
                this.dataForm.logicId = obj.cameraName
              }
            }, 800)
          }
        }
        this.dataForm.authorizationMode1 = this.dataForm.authorizationMode ? this.dataForm.authorizationMode.split(',').map(Number) : [] // 回显授权方式
      } else {
        this.platformList = []
        this.dataForm.authorizationMode1 = []
      }
      this.$nextTick(() => {
        this.getqQueryList()
        this.getbrandList()
        this.getlocationList()
        if (this.dataForm.id) {
          this.getDataInfo().then(res => {
            if (res.code !== 0) {
              return
            }
            let list = []
            for (let i = 0; i < res.data.url.length; i++) {
              let arr = {}
              arr.name = res.data.url[i]
              arr.url = res.data.url[i]
              list.push(arr)
            }
            if (res.data.url) {
              if (this.$refs.fileUpload) {
                this.$refs.fileUpload.init(list)
              }
            }
          })
        }
      })
      this.visible = true
    },
    getlogicList () {
      if (!this.dataForm.deviceType || !this.dataForm.platform) {
        return
      }
      this.$http.get(`tb/device/thirdPlatDevice?deviceType=${this.dataForm.deviceType}&thirdPlatId=${this.dataForm.platform}&cameraName=`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        } else {
          if (res.data) {
            this.logicList = res.data
            this.logicList.forEach(item => {
              item.value = item.cameraIndexCode
            })
          } else {
            this.logicList = []
          }
        }
      })
    },
    onselect (val) {
      if (val) {
        this.dataForm.dockingMethod = 1
      }
    },
    changes (val) {
      if (val) {
        if (Array.isArray(val) && val.length > 1) {
          this.dataForm.unifiedAuthorization = 1
        }
      }
    },
    querySearchAsync (queryString, cb) {
      clearTimeout(this.timeout)
      if (!this.dataForm.deviceType || !this.dataForm.platform) {
        return
      }
      this.getlogicList()
      this.timeout = setTimeout(() => {
        cb(this.logicList ? this.logicList.filter(this.createStateFilter(queryString)) : [])
      }, 1000 * Math.random())
    },
    createStateFilter (queryString) {
      return (state) => {
        return (state.cameraName.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleSelect (item) {
      if (item) {
        this.dataForm.logicId = item.cameraName
      } else {
        this.dataForm.logicId = ''
      }
    },
    getmanufacturersToString (_id) {
      return this.manufacturersList.find(item => item.id === _id)['name']
    },
    getbrandList () {
      this.$http.get('tb/deviceBrand/getAll').then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.brandList = res.data
      })
    },
    getlocationList () {
      this.$http.get('tb/area/allNameList').then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.locationList = res.data
      })
    },
    getqQueryList () {
      this.$http.get(`tb/thirdPlatform/queryList?type=2&manufacturers=`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.platformList = []
        if (res.data.length > 0) {
          this.platformList = res.data
        }
        // manufacturers===10是无效数据
        this.platformList.forEach((item, index) => {
          if (item.manufacturers === 10) {
            this.platformList.splice(index, 1)
          }
        })
      })
    },
    closeDialog () {
      //   this.$refs.dataForm.resetFields()
      // this.dataForm.type1 = 0
      this.dataForm.authorizationMode = ''
      this.dataForm.authorizationMode1 = []
      this.dataForm.name = ''
      this.dataForm.subsystem1 = []
      this.dataForm.subsystem = []
      this.dataForm.template = ''
      this.dataForm.type = ''
      // this.dataForm.status = 0
      this.dataForm.marks = ''
      this.dataForm.url = []
      this.dataForm.model = ''
      this.dataForm.brandId = ''
      this.dataForm.aid = ''
      this.dataForm.supplier = ''
      this.dataForm.linkMan = ''
      this.dataForm.link = ''
      this.dataForm.deviceType = ''
      this.dataForm.deviceId = ''
      this.dataForm.platform = ''
      this.dataForm.id = ''
      this.dataForm.energy = 1
      this.dataForm.logicId = ''
      this.dataForm.logicId = ''
      this.dataForm.unifiedAuthorization = 1
      this.dataForm.dockingMethod = 0
      this.hasID = false
      this.$emit('callBack')
      this.visible = false
    },
    handleImgRemove (url) {
      let index = this.dataForm.url.findIndex(item => item === url.url)
      this.dataForm.url.splice(index, 1)
      return this.deleteData({
        url: this.mixinViewModuleOptions.deleteImgURL,
        paramData: { files: url.url },
        isLoading: false
      })
    },
    successImgLoad (name, url) {
      this.dataForm.url.push(url)
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            const url = this.hasID === true
              ? this.mixinViewModuleOptions.updateURL
              : this.mixinViewModuleOptions.addURL
            this.dataForm.subsystem = this.dataForm.subsystem1.join()
            this.dataForm.authorizationMode = this.dataForm.authorizationMode1.join()
            let obj = this.dataForm
            if (this.dataForm.dockingMethod !== 1) {
              obj.logicId = ''
              obj.platform = ''
            } else if (this.dataForm.dockingMethod === 1) {
              if (this.dataForm.logicId) { // 回显逻辑ID
                if (this.dataForm.platform) {
                  let objlogic = this.logicList.find(item => item.cameraName === this.dataForm.logicId)
                  if (objlogic) {
                    obj.logicId = objlogic.value
                  } else {
                    obj.logicId = this.dataForm.logicId
                  }
                }
              }
              if (!this.dataForm.platform) {
                this.$message.error('对接平台为第三方时请选择对接平台')
                document.getElementById('platformBtn').classList.add('revolveShake')
                setTimeout(() => {
                  document.getElementById('platformBtn').classList.remove('revolveShake')
                }, 600)
                return
              }
            }
            if (this.hasID === false) {
              this.dataForm.iot = 1
              this.$http.post(url, obj).then(({ data: res }) => {
                if (res.code !== 0) {
                  let obj1 = this.logicList.find(item => item.cameraIndexCode === this.dataForm.logicId)
                  if (obj1) {
                    this.dataForm.logicId = obj1.cameraName
                  }
                  return this.$message.error(res.msg)
                }
                this.$message.success('新增成功')
                this.closeDialog()
              })
            } else {
              this.$http.put(url, obj).then(({ data: res }) => {
                if (res.code !== 0) {
                  let obj1 = this.logicList.find(item => item.cameraIndexCode === this.dataForm.logicId)
                  if (obj1) {
                    this.dataForm.logicId = obj1.cameraName
                  }
                  return this.$message.error(res.msg)
                }
                this.$message.success('保存成功')
                this.closeDialog()
              })
            }
          }
        })
      },
      1000,
      { leading: true, trailing: false }
    )
  }
}
</script>

<style lang="scss" scoped>
.revolveShake {
  animation-name: spin;
  animation-duration: 0.5s;
}

@keyframes spin {
  16% {
    transform: rotate(0deg);
  }

  32% {
    transform: rotate(4deg);
  }

  48% {
    transform: rotate(-4deg);
  }

  64% {
    transform: rotate(4deg);
  }

  80% {
    transform: rotate(-4deg);
  }

  100% {
    transform: rotate(0deg);
  }
}

.label-left-form {
  display: flex;
}

.content {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  margin-bottom: 10px;

  .title {
    min-width: 80px;
    margin: 0 10px;
    vertical-align: -8%;
  }

  .line {
    width: 100%;
    border-top: 1px solid #ccc;
  }
}
</style>
